#!/usr/bin/python
# -*- coding: UTF-8 -*-

from sqlalchemy import create_engine
import tushare as ts
import pandas as pd
import time as threadTime
from datetime import time,timedelta,datetime


# df = ts.get_tick_data('600377', date='2017-05-17')
# df.head(10)
# print(df)
# ts.get_hist_data('600848',start='2015-01-05',end='2015-01-09')
# 格力 000651  康美药业 600518  宁沪高速 600377  中国建筑 601668  
# 50ETF 510050  农业银行 601288  招商银行 600036  中国银行 601988  宝钢包装 601968
# 上证指数  000001

# 初始化mysql引擎
engine = create_engine('mysql://root:@127.0.0.1/stock?charset=utf8')


# # 获取上市日期
# df = ts.get_stock_basics()
# print(df)
# #存入数据库
# df.to_sql('ipo_date',engine,if_exists='append')
# stockCodeList = ['000651', '600518', '600377', '601668', '601288', '600036', '601988', '601968','000001', '002300']
stockCode = '000001'

ipoStr='19901231'
ipoDT= datetime.strptime(ipoStr, '%Y%m%d')

oneYear = timedelta(days=365)
oneDay=timedelta(days=1)
dStartDate=ipoDT
startDate=dStartDate.strftime('%Y-%m-%d')
dEndDate=dStartDate+oneYear
endDate=dEndDate.strftime('%Y-%m-%d')
dNow=datetime.now()

while dNow>dEndDate:
    print "start to get %s : %s -- %s " % (stockCode,startDate,endDate)
    df=ts.get_h_data(stockCode,start=startDate,end=endDate,index=True)
    #存入数据库
    df.to_sql(stockCode,engine,if_exists='append',index_label='date')
    print "\n get %s  date:%s - %s successful!" % (stockCode,startDate,endDate)
    threadTime.sleep(5)
    dStartDate=dEndDate+oneDay
    startDate=dStartDate.strftime('%Y-%m-%d')
    dEndDate=dStartDate+oneYear
    endDate=dEndDate.strftime('%Y-%m-%d')

endDate=dNow.strftime('%Y-%m-%d')
print "start to get %s : %s -- %s " % (stockCode,startDate,endDate)
df=ts.get_h_data(stockCode,start=startDate,end=endDate,index=True)
#存入数据库
df.to_sql(stockCode,engine,if_exists='append',index_label='date')
print "\n get %s  date:%s - %s successful!" % (stockCode,startDate,endDate)
threadTime.sleep(5)
print "%s day info all done!" % (stockCode)
